package com.itcoon.cloud.framework.utils;/**
 * @author Athric Yu
 * 2025/1/14
 **/

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executor;
import java.util.function.Consumer;

/**
 * @author Athric Yu
 * 2025/1/14
 **/
public class NacosConfigUtil {

    public static NacosConfigManager nacosConfigManager = SpringUtils.getBean(NacosConfigManager.class);

    public static InputStream getInputStream(String fileName, String groupName) {
        String configContent = null;
        try {
            configContent = nacosConfigManager.getConfigService().getConfig(fileName, groupName, 3000L);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.hasText(configContent)) {
            return new ByteArrayInputStream(configContent.getBytes(StandardCharsets.UTF_8));
        }
        return null;
    }

    public static void addListener(String fileName, String groupName, Listener listener) {
        try {
            nacosConfigManager.getConfigService().addListener(fileName, groupName, listener);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    public static void refresh(String fileName, String groupName, Consumer<String> configConsumer) {
        try {
            nacosConfigManager.getConfigService().addListener(fileName, groupName, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                /**
                 *
                 * @param configInfo aaa=bb
                 */
                @Override
                public void receiveConfigInfo(String configInfo) {
                    configConsumer.accept(configInfo);
                }
            });
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }
}
